package com.mac.hosp_pre.user.service.impl;

import cn.hutool.core.collection.CollectionUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.mac.hosp_pre.base.UserBaseDto;
import com.mac.hosp_pre.enums.AuthStatusEnum;
import com.mac.hosp_pre.except.ResultCodeEnum;
import com.mac.hosp_pre.except.ServiceException;
import com.mac.hosp_pre.handler.RefreshTokenHandler;
import com.mac.hosp_pre.user.constant.UserConstant;
import com.mac.hosp_pre.user.entity.UserInfo;
import com.mac.hosp_pre.user.enums.UserResultCodeEnum;
import com.mac.hosp_pre.user.mapper.UserInfoMapper;
import com.mac.hosp_pre.user.model.req.LoginReqDto;
import com.mac.hosp_pre.user.model.req.UserAuthReqDto;
import com.mac.hosp_pre.user.model.req.UserInfoQueryReqDto;
import com.mac.hosp_pre.user.model.resp.PatientRespDto;
import com.mac.hosp_pre.user.model.resp.UserRespDto;
import com.mac.hosp_pre.user.service.PatientService;
import com.mac.hosp_pre.user.service.UserInfoService;
import com.mac.hosp_pre.user.util.RedisUtil;
import com.mac.hosp_pre.util.JwtUtil;
import lombok.extern.slf4j.Slf4j;
import me.chanjar.weixin.common.bean.WxOAuth2UserInfo;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;

@Slf4j
@Service
public class UserInfoServiceImpl extends ServiceImpl<UserInfoMapper, UserInfo> implements UserInfoService {

    @Autowired
    private RedisUtil redisUtil;

    @Autowired
    private PatientService patientService;

    @Transactional(rollbackFor = Exception.class)
    @Override
    public Map<String, Object> loginUser(LoginReqDto login) {
        String phone = login.getPhone();
        String code = login.getCode();
        //判断手机号和验证码是否为空
        if(StringUtils.isAnyBlank(code,phone)) {
            throw new ServiceException(ResultCodeEnum.PARAM_EMPTY_ERROR);
        }

        //判断手机验证码和输入的验证码是否一致
        String redisCode = redisUtil.getCacheObject(UserConstant.REDIS_LOGIN_CODE_PREFIX+phone);
        if(!code.equals(redisCode)) {
            throw new ServiceException(UserResultCodeEnum.CODE_ERROR.getCode(),"验证码不一致");
        }
        //绑定手机号码
        UserRespDto userInfo = null;
        if(StringUtils.isNotBlank(login.getOpenid())) {
            userInfo = this.selectWxInfoOpenId(login.getOpenid());
            if(null != userInfo) {
                userInfo.setPhone(login.getPhone());
                UserInfo user = new UserInfo();
                user.setId(userInfo.getId());
                user.setPhone(phone);
                this.updateById(user);
            } else {
                throw new ServiceException(ResultCodeEnum.NOT_EXISTS_ERROR);
            }
        }

        //如果userinfo为空，进行正常手机登录
        if(userInfo == null) {
            //判断是否第一次登录：根据手机号查询数据库，如果不存在相同手机号就是第一次登录
            UserInfo user = baseMapper.selectOne(new LambdaQueryWrapper<UserInfo>().eq(UserInfo::getPhone,phone));
            if(user == null) { //第一次使用这个手机号登录
                //添加信息到数据库
                user = new UserInfo();
                user.setUserName("");
                user.setPhone(phone);
                user.setStatus(1);
                baseMapper.insert(user);
                userInfo.setId(user.getId());
            }
        }else if (userInfo.getStatus() == 0){
            throw new ServiceException(UserResultCodeEnum.LOGIN_DISABLED_ERROR.getCode(),UserResultCodeEnum.LOGIN_DISABLED_ERROR.getMsg());
        }

        //不是第一次，直接登录
        Map<String, Object> map = new HashMap<>();
        String name = userInfo == null ? "" : userInfo.getUserName();
        if(StringUtils.isEmpty(name)) {
            name = userInfo.getNickName();
        }
        if(StringUtils.isEmpty(name)) {
            name = login.getPhone();
        }
        map.put("name",name);

        //jwt生成token字符串
        String token = JwtUtil.createToken(userInfo.getId(), name);
        map.put("token",token);
        RefreshTokenHandler consumer = (loginRedisKey, expiration, userLogin) -> {
            redisUtil.setCacheObject(loginRedisKey,userLogin,expiration, TimeUnit.SECONDS);
        };
        UserBaseDto baseDto = new UserBaseDto();
        BeanUtils.copyProperties(userInfo,baseDto);
        baseDto.setUserName(name);
        JwtUtil.setRedisUserInfo(null,token,baseDto,false,consumer);
        return map;
    }

    @Override
    public UserRespDto selectWxInfoOpenId(String openid) {
        UserInfo userInfo = baseMapper.selectOne(new LambdaQueryWrapper<UserInfo>().eq(UserInfo::getOpenId,openid));
        if (null != userInfo){
            UserRespDto userRespDto = new UserRespDto();
            BeanUtils.copyProperties(userInfo,userRespDto);
            return userRespDto;
        }
        return null;
    }

    @Override
    public void userAuth(Long userId, UserAuthReqDto userAuth) {
        //根据用户id查询用户信息
        UserInfo userInfo = baseMapper.selectById(userId);
        if (null == userInfo){
            throw new ServiceException(ResultCodeEnum.NOT_EXISTS_ERROR);
        }
        //设置认证信息
        //认证人姓名
        userInfo.setUserName(userAuth.getName());
        //其他认证信息
        userInfo.setCertificatesType(userAuth.getCertificateType());
        userInfo.setCertificatesNo(userAuth.getCertificateNo());
        userInfo.setCertificatesUrl(userAuth.getCertificateUrl());
        userInfo.setAuthStatus(AuthStatusEnum.AUTH_RUN.getStatus());
        //进行信息更新
        baseMapper.updateById(userInfo);
    }

    @Override
    public IPage<UserRespDto> selectPage(UserInfoQueryReqDto userInfoQuery) {
        String name = userInfoQuery.getKeyword(); //用户名称
        Integer status = userInfoQuery.getStatus();//用户状态
        Integer authStatus = userInfoQuery.getAuthStatus(); //认证状态
        String createTimeBegin = userInfoQuery.getCreateTimeBegin(); //开始时间
        String createTimeEnd = userInfoQuery.getCreateTimeEnd(); //结束时间
        Page<UserInfo> page = Page.of(userInfoQuery.getPageNo(), userInfoQuery.getPageSize());
        LambdaQueryWrapper<UserInfo> wrapper = new LambdaQueryWrapper<>();
        wrapper.like(StringUtils.isNotBlank(name), UserInfo::getUserName, name)
                .eq(null != status, UserInfo::getStatus, status)
                .eq(null != authStatus, UserInfo::getAuthStatus, authStatus)
                .ge(null != createTimeBegin, UserInfo::getCreateTime, createTimeBegin)
                .le(null != createTimeEnd, UserInfo::getCreateTime, createTimeEnd)
                .orderByDesc(UserInfo::getId);
        //调用mapper的方法
        IPage<UserInfo> pages = baseMapper.selectPage(page, wrapper);
        //编号变成对应值封装
        if (CollectionUtil.isNotEmpty(pages.getRecords())){
            return pages.convert(item -> {
                UserRespDto userInfo = new UserRespDto();
                BeanUtils.copyProperties(item,userInfo);
                this.packageUserInfo(userInfo);
                return userInfo;
            });
        }
        return new Page<>(userInfoQuery.getPageNo(), userInfoQuery.getPageSize());
    }

    //编号变成对应值封装
    private void packageUserInfo(UserRespDto userInfo) {
        //处理认证状态编码
        userInfo.setAuthStatusString(AuthStatusEnum.getStatusNameByStatus(userInfo.getAuthStatus()));
        //处理用户状态 0  1
        String statusString = userInfo.getStatus().intValue()==0 ?"锁定" : "正常";
        userInfo.setStatusString(statusString);
    }

    @Override
    public void lock(Long userId, Integer status) {
        if(status.intValue()==0 || status.intValue()==1) {
            UserInfo userInfo = baseMapper.selectById(userId);
            if (null == userInfo){
                throw new ServiceException(ResultCodeEnum.NOT_EXISTS_ERROR);
            }
            UserInfo user = new UserInfo();
            user.setId(userId.longValue());
            user.setStatus(status);
            baseMapper.updateById(user);
        }
    }

    @Override
    public Map<String, Object> detail(Long userId) {
        Map<String,Object> map = new HashMap<>();
        //根据userid查询用户信息
        UserInfo user = baseMapper.selectById(userId);
        if (null != user){
            UserRespDto respDto = new UserRespDto();
            BeanUtils.copyProperties(user,respDto);
            this.packageUserInfo(respDto);
            map.put("userInfo",respDto);
        }
        //根据userid查询就诊人信息
        List<PatientRespDto> patientList = patientService.findAllUserId(userId);
        map.put("patientList",patientList);
        return map;
    }

    @Override
    public void approval(Long userId, Integer authStatus) {
        if(authStatus.intValue()==2 || authStatus.intValue()==-1) {
            UserInfo userInfo = baseMapper.selectById(userId);
            if (null == userInfo){
                throw new ServiceException(ResultCodeEnum.NOT_EXISTS_ERROR);
            }
            userInfo.setAuthStatus(authStatus);
            baseMapper.updateById(userInfo);
        }
    }

    @Override
    public UserRespDto getOrSaveUserInfoOpenId(WxOAuth2UserInfo wxMpUser, String openId) {
        UserInfo userInfo = this.getOne(new LambdaQueryWrapper<UserInfo>().eq(UserInfo::getOpenId, openId).last(" limit 1 "));
        if (userInfo == null){
            userInfo = new UserInfo();
            userInfo.setOpenId(openId);
            userInfo.setNickName(wxMpUser.getNickname());
            userInfo.setAvatar(wxMpUser.getHeadImgUrl());
            userInfo.setUnionId(wxMpUser.getUnionId());
            userInfo.setStatus(1);
            this.save(userInfo);
        }
        String name = userInfo.getUserName();
        if(StringUtils.isEmpty(name)) {
            name = userInfo.getNickName();
        }
        if(StringUtils.isEmpty(name)) {
            name = userInfo.getPhone();
        }
        UserRespDto userInfoReply = new UserRespDto();
        BeanUtils.copyProperties(userInfo,userInfoReply);
        userInfoReply.setUserName(name);
        //授权完成之后，跳转具体功能页面
        //生成token，按照一定规则生成字符串，可以包含用户信息
        String token = JwtUtil.createToken(userInfo.getId(),userInfo.getUserName());
        userInfoReply.setToken(token);
        //redis 缓存用户信息
        RefreshTokenHandler consumer = (loginRedisKey, expiration, userLogin) -> {
            redisUtil.setCacheObject(loginRedisKey,userLogin,expiration, TimeUnit.SECONDS);
        };
        UserBaseDto baseDto = new UserBaseDto();
        BeanUtils.copyProperties(userInfo,baseDto);
        baseDto.setUserName(name);
        JwtUtil.setRedisUserInfo(null,token,baseDto,false,consumer);
        return userInfoReply;
    }
}
